<template>
  <div class="container">
    <div class="query-container">
      <el-card class="query-card">
        <el-form
          :model="queryForm"
          class="query-form"
          ref="formRef"
          label-width="120px"
        >
          <el-row>
            <el-col :span="6">
              <el-form-item label="名称">
                <el-input v-model="queryForm.name" placeholder="请输入名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="代码">
                <el-input v-model="queryForm.code" placeholder="请输入代码" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-button type="primary" @click="handleSearch()">查询</el-button>
              <el-button @click="reset()">重置</el-button>
              <el-button type="warning" @click="handleAdd()">新增</el-button>
              <el-button type="danger" @click="batchDelete()">删除</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <div class="table-container">
      <el-table
        :data="tableData"
        size="mini"
        style="width: 100%"
        row-key="id"
        lazy
        border
        default-expand-all
        ref="multipleTable"
        @select-all="selectAll"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ height: '30px !important', fontSize: '12px' }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="id" label="ID" v-if="false" />
        <el-table-column prop="name" label="类别名称" />
        <el-table-column prop="code" label="类别代码" />
        <el-table-column prop="remark" label="说明" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-switch
              style="display: block"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(scope.row.id)"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { assetCategory } from "@/api/assetCategory.js";
export default {
  data() {
    return {
      tableData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      status: "",
      multipleSelection: [],
      allSelected: false,
      filteredData: [],
      page: 1,
      limit: 20,
      count: 0,
      queryForm: {
        name: "",
        code: "",
        status: "",
      },
    };
  },
  watch: {},
  created() {
    this.getAssetCategoryList();
  },
  methods: {
    getAssetCategoryList() {
      assetCategory
        .list({ page: this.page, limit: this.limit, ...this.queryForm })
        .then((response) => {
          const dataFromDB = response.data; // 假设 response.data 是你需要的数据
          // 渲染状态
          for (let i = 0; i < dataFromDB.length; i++) {
            const element = dataFromDB[i];
            if (element.status === 1) {
              element.status = "1";
            } else {
              element.status = "0";
            }
          }
          this.tableData = this.buildTree(dataFromDB);
          this.count = response.count;
        });
    },
    buildTree(data) {
      const tree = [];
      const mappedData = {};
      // 将数组转为对象方便查找
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        mappedData[item.id] = { ...item, children: [] };
      }
      // 构建树
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (item.parentId === null) {
          tree.push(mappedData[item.id]);
        } else {
          if (mappedData[item.parentId]) {
            mappedData[item.parentId].children.push(mappedData[item.id]);
          }
        }
      }
      return tree;
    },
    handleSearch() {
      // this.getAssetCategoryList();
      this.filteredData = this.filterData(this.tableData, this.queryForm);
      this.allSelected = false; // Reset all selected status on new search
      this.tableData = this.filteredData;
    },
    filterData(data, query) {
      const result = [];
      data.forEach((item) => {
        const children = item.children
          ? this.filterData(item.children, query)
          : [];
        if (
          (item.name.includes(query.name) && item.code.includes(query.code)) ||
          children.length > 0
        ) {
          const newItem = { ...item };
          if (children.length > 0) {
            newItem.children = children;
          } else {
            delete newItem.children; // 如果没有子节点，删除这个属性
          }
          result.push(newItem);
        }
      });
      return result;
    },
    reset() {
      this.queryForm = {};
      this.getAssetCategoryList();
    },
    handleAdd() {
      // 跳转新增页面
      this.$router.push({
        name: "AssetCategoryAdd",
      });
    },
    batchDelete() {
      const ids = this.multipleSelection.map((item) => item.id);
      if (ids.length === 0) {
        this.$message({
          message: "请选择要删除的数据",
          type: "warning",
        });
        return;
      }
      const batchDeleteDto = {
        ids: ids,
      };
      // console.log(batchDeleteDto);
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除
          assetCategory.deleteBatch(batchDeleteDto).then((response) => {
            this.$message({
              message: response.msg,
              type: "success",
            });
            this.getAssetCategoryList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 全选 / 取消全选
    selectAll() {
      const table = this.$refs.multipleTable;
      this.allSelected = !this.allSelected;
      if (table) {
        this.tableData.forEach((item) => {
          if (this.allSelected) {
            this.toggleSelection(item, true);
          } else {
            this.toggleSelection(item, false);
          }
        });
      }
    },
    toggleSelection(item, selected) {
      const table = this.$refs.multipleTable;
      table.toggleRowSelection(item, selected);
      if (item.children) {
        item.children.forEach((child) => this.toggleSelection(child, selected));
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //修改
    handleStatusChange(row) {
      // console.log("当前节点状态:", row.status);
      assetCategory.update(row).then((response) => {
        this.$message({
          message: response.msg,
          type: "success",
        });
      });
      // 刷新
      this.getAssetCategoryList();
    },
    handleEdit(id) {
      // 跳转编辑页面
      this.$router.push({
        name: "assetCategoryEdit",
        params: { id: id },
      });
    },
    handleDelete(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除
          assetCategory.delete(id).then((response) => {
            this.$message({
              message: response.msg,
              type: "success",
            });
            this.getAssetCategoryList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.limit = val;
      this.getAssetCategoryList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.getAssetCategoryList();
    },
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.query-container {
  margin-bottom: 20px;
}

.query-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* .button-group {
  display: flex;
  justify-content: space-between;
} */

.table-container {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  background-color: white;
}

.pagination-container {
  margin-top: 20px;
}
</style>
